package pl.ncdc.web.login.server.service;

import java.io.File;

import pl.ncdc.web.login.client.Credentials;
import pl.ncdc.web.login.client.service.AuthenticationResult;
import pl.ncdc.web.login.client.service.AuthenticationService;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * Demo version of {@link AuthenticationService}.
 * <p>
 * Created on Apr 17, 2008
 *
 * @author hshsce
 * @version $Id: DemoAuthenticationService.java 193 2009-04-09 12:36:36Z hshsce $
 */
public class DemoAuthenticationService extends RemoteServiceServlet implements AuthenticationService {

	private final File m_userImagesDir = new File("ncdc-web-login-demo/src/main/java/pl/ncdc/web/login/public/images/users");

	public AuthenticationResult login(final Credentials credentials) {
		final AuthenticationResult result;
		final String uid = credentials.getUid();
		if ((new File(m_userImagesDir, uid + ".jpg")).exists()) {
			if ((uid != null) && uid.equals(credentials.getPassword())) {
				result = AuthenticationResult.OK;
				getThreadLocalRequest().getSession().setAttribute("AutenticationStatus", AuthenticationResult.OK);
			} else {
				result = AuthenticationResult.INVALID_PASSWORD;
			}
		} else {
			result = AuthenticationResult.INVALID_UID;
		}
		if (result != AuthenticationResult.OK) {
			try {
				Thread.sleep(1000); //just block this thread for a while
			} catch (final InterruptedException e) {
				//nothing to do
			}
		}
		return result;
	}

	public void logout() {
		getThreadLocalRequest().getSession().invalidate();
	}

	/**
	 * @see pl.ncdc.web.login.client.service.AuthenticationService#isAuthenticated()
	 */
	public boolean isAuthenticated() {
		final AuthenticationResult result = (AuthenticationResult) getThreadLocalRequest().getSession().getAttribute("AutenticationStatus");
		return (result == AuthenticationResult.OK);
	}

}
